import React, { useState, useRef, useCallback } from "react";
import { LogoutOutlined, EditOutlined, UserOutlined } from "@ant-design/icons";
import { message, Menu, Spin } from "antd";
import { history, useModel } from "umi";
import { stringify } from "querystring";
import { outLogin } from "@/services/admin";
import HeaderDropdown from "../HeaderDropdown";
import styles from "./index.less";
import { ModalForm, ProFormText } from "@ant-design/pro-form";
import { updatePassword } from "@/services/admin";

const AvatarDropdown = ({ menu }) => {
  const formRef = useRef();

  const [modalVisit, setModalVisit] = useState(false);

  const { initialState, setInitialState } = useModel("@@initialState");

  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    await outLogin();
    const { query = {}, search, pathname } = history.location;
    const { redirect } = query; // Note: There may be security issues, please note
    localStorage.removeItem("adminInfo");
    localStorage.removeItem("access_token");
    setInitialState((s) => ({ ...s, currentUser: undefined }));
    if (window.location.pathname !== "/admin/login" && !redirect) {
      history.replace({
        pathname: "/admin/login",
      });
    }
  };

  const onMenuClick = useCallback(
    (event) => {
      const { key } = event;
      if (key === "logout") {
        loginOut();
        return;
      }

      if (key === "updatePwd") {
        setModalVisit(true);
      }
    },
    [setInitialState]
  );
  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;
  console.log("currentUser===",currentUser);

  if (!currentUser || !currentUser.nickName) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      {/* {menu && (
        <Menu.Item key="center">
          <UserOutlined />
          个人中心
        </Menu.Item>
      )}
      {menu && (
        <Menu.Item key="settings">
          <SettingOutlined />
          个人设置
        </Menu.Item>
      )}
      {menu && <Menu.Divider />} */}

      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
      {/* <Menu.Item key="updatePwd">
        <EditOutlined />
        修改密码
      </Menu.Item> */}
    </Menu>
  );
  return (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          {/* <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" /> */}
          <span className={`${styles.name} anticon`}>{currentUser.nickName}</span>
        </span>
      </HeaderDropdown>

      <ModalForm
        formRef={formRef}
        visible={modalVisit}
        onVisibleChange={setModalVisit}
        key="modal"
        layout="horizontal"
        title="修改密码"
        width={600}
        onFinish={async (values) => {
          const res = await updatePassword({
            id: currentUser.id,
            ...values,
          });
          if (res.data) {
            message.success("修改成功");
            loginOut();
            return true;
          }
        }}
        initialValues={{
          type: 0,
        }}
        modalProps={{
          onCancel: () => {
            formRef.current?.resetFields();
          },
        }}
      >
        <ProFormText
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        />
      </ModalForm>
    </>
  );
};

export default AvatarDropdown;
